# -*- coding: utf-8 -*-

import wsgiref.handlers
import sys
import os
import string
import hashlib
import codecs
import random
import re
import cgi
import datetime
import time
import math
import pickle
import logging
import Cookie
import urllib
import urllib2

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp

webapp.template.register_template_library('customfilters')

from math import sqrt
from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import search
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from datetime import datetime
from google.appengine.api import images
from models import *
from utilities import *
from django.utils import simplejson as json
from django.core.validators import email_re
from google.appengine.ext.webapp import template

from gaesessions import get_current_session

from cart import *

# Set to true if we want to have our webapp print stack traces, etc
_DEBUG = True

def redirect_with_msg(h, msg, dst='/'):
  get_current_session()['msg'] = msg
  h.redirect(dst)

class BaseRequestHandler(webapp.RequestHandler):
  """Supplies a common template generation function.

  When you call generate(), we augment the template variables supplied with
  the variables present in this function.
  """
  def generate(self, template_name, template_values={}, mime = "text/html"):

    session = get_current_session()
    if session.has_key('numProd'):
      numProd = session['numProd']
    else:
      numProd = 0

    if session.has_key('msg'):
      message = session['msg']
      del session['msg'] # only show the message once
    else:
      message = ''

    values = {
      'request': self.request,
      'application_name': 'carritonero',
      'numProd': numProd,
      'message': message,
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('templates', template_name))
    if mime == "text/xml":
      self.response.headers['Content-Type'] = "text/xml"
    self.response.out.write(template.render(path, values, debug=_DEBUG))


class Index(BaseRequestHandler):
  def get(self):
    queryproducts = Product.all()
    queryproducts.order('prodId')
    products = queryproducts.fetch(100)

    template_values = {
      'products': products
    }
    self.generate('index.html', template_values)


class PopulateProducts(BaseRequestHandler):
  def get(self):
    product = Product(name = "Perrito Caliente", prodId = 1)
    product.put()

    product = Product(name = "Hamburguesa", prodId = 2)
    product.put()

    product = Product(name = "Pizza", prodId = 3)
    product.put()


class Cart(BaseRequestHandler):
  def get(self):
    session = get_current_session()
    if session.has_key('products'):
      products = session['products']
      if len(products) > 0:
        emptyCart = False
      else:
        emptyCart = True
    else:
      emptyCart = True

    productsInCart = []
    if not emptyCart:
      for prodId in products:
        queryproducts = Product.all()
        queryproducts.filter(' prodId = ', int(prodId))
        products = queryproducts.fetch(1)
        product= products[0]
        productsInCart.append(product)

    template_values = {
      'emptyCart': emptyCart,
      'products': productsInCart,
    }
    self.generate('carrito.html', template_values)
  
def main():
  urlmap = [
            ('/', Index),
            ('/cart/add/', addToCart),
            ('/cart/remove/', removeFromCart),
            ('/popprods/', PopulateProducts),
            ('/cart', Cart)
           ]

  application = webapp.WSGIApplication(urlmap, debug=_DEBUG)
  run_wsgi_app(application)

if __name__ == "__main__":
  main()